package com.mindata.blockmanager.manager;

import com.mindata.blockmanager.bean.GridResultDto;
import com.mindata.blockmanager.bean.QueryPage;
import com.mindata.blockmanager.model.MemberGroup;
import com.mindata.blockmanager.repository.MemberGroupRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wuweifeng wrote on 2018/3/7.
 */
@Component
public class MemberGroupManager {
    @Resource
    private MemberGroupRepository memberGroupRepository;

    public GridResultDto pagingGroupList(QueryPage page) {
        Sort sort = new Sort(page.getOrder(), page.getSort());    //排序
        Pageable pageable = new PageRequest(page.getPage(), page.getRows(), sort);
        Page<MemberGroup> pages = memberGroupRepository.findAll(pageable);
        return GridResultDto.createGridResultDto(pages.getContent(), pages.getTotalElements());
    }

    public void addMemberGroup(MemberGroup group) {
        memberGroupRepository.save(group);
    }

    public void delMemberGroup(long id) {
        memberGroupRepository.delete(id);
    }

    public MemberGroup findById(long id) {
        return memberGroupRepository.findOne(id);
    }

    public void updateMemberGroup(MemberGroup group) {
        memberGroupRepository.save(group);
    }

    public List<MemberGroup> findAll() {
        return memberGroupRepository.findAll();
    }

    public Map<Integer, String> getGroupMap() {
        Map<Integer, String> groupMap = new HashMap<>();
        List<MemberGroup> groups = findAll();
        groups.forEach(e -> {
            groupMap.put(e.getGroupId(), e.getName());
        });
        return groupMap;
    }
}
